<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/mine/mineBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="任务详情" :showBack="true"></cusHeaderVue>
		<scroll-view scroll-y="true"
			:style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`,height: `calc(100vh - ${scrollerHeight} - 90rpx)`}">
			<view class="contBox">
				<view class="contBig">
					<view class="contTop">
						<view class="contTit">
							<view class="contName">
								任务信息
							</view>
							<view class="contStatus">
								<image src="/static/mine/ywclb.png" mode=""></image>
							</view>
						</view>
						<view class="contLi">
							<text>任务类型：</text>{{ getTaskTypeText(taskData.dxTaskDO.taskType) }}
						</view>
						<view class="contLi">
							<text>任务描述：</text>{{ taskData.dxTaskDO.description || '无描述' }}
						</view>
						<view class="contLi">
							<text>完成时间：</text>{{ formatDate1(taskData.dxTaskDO.updateTime) }}
						</view>
						<view class="contLi">
							<text>下发人：</text>{{ taskData.dxTaskDO.createUserName || '未知' }}
						</view>
						<view class="contLi" v-if="taskData.dxTaskDO.fileUrl && taskData.dxTaskDO.fileUrl !== 'www.baidu.com'">
							<text>任务附件：</text>
							<text class="linkText" @click="openFile(taskData.dxTaskDO.fileUrl)">{{ taskData.dxTaskDO.fileUrl }}</text>
						</view>
					</view>
				</view>
				<view class="contBig" v-if="taskData.originalData">
					<view class="contTop">
						<view class="contTit">
							<view class="contName">
								反馈信息
							</view>
						</view>
						<view class="contLi">
							<text>反馈内容：</text>{{ taskData.originalData.description || '无反馈内容' }}
						</view>
						<view class="contLi">
							<text>反馈时间：</text>{{ formatDate(taskData.dxTaskDO.updateTime) }}
						</view>
						<view class="contLi">
							<text>反馈人：</text>{{ taskData.originalData.nickName || '未知' }}
						</view>
						<view class="contLi" v-if="taskData.originalData.imagePath && getImageList(taskData.originalData.imagePath).length > 0">
							<text>反馈图片：</text>
							<view class="contImgBox">
								<view 
									class="contImageLi" 
									v-for="(image, index) in getImageList(taskData.originalData.imagePath)" 
									:key="index"
									@click="previewImageList(getImageList(taskData.originalData.imagePath), index)"
								>
									<image :src="image" mode="aspectFill"></image>
								</view>
							</view>
						</view>
						<view class="contLi" v-if="taskData.originalData.fileName && getFileList(taskData.originalData.fileName).length > 0">
							<text>反馈附件：</text>
							<view class="fileList">
								<text 
									class="linkText fileItem" 
									v-for="(fileName, index) in getFileList(taskData.originalData.fileName)" 
									:key="index"
									@click="openFile(getFileUrlList(taskData.originalData.fileUrl)[index] || '')"
								>
									📄 {{ fileName }}
								</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app';
	import {
		ref
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	const scrollerHeight = ref('');
	// 任务数据
	const taskData = ref({
		// 默认值，将从本地存储获取实际数据
		dxTaskDO: {
			taskType: '',
			description: '',
			completionTime: '',
			createUserName: '',
			fileUrl: ''
		},
		originalData: {
			description: '',
			updateTime: '',
			nickName: '',
			imagePath: '',
			fileName: '',
			fileUrl: ''
		}
	});
	

	const formatDate1 = (timestamp) => {
		if (!timestamp) return '';
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	}


	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}

	// 日期格式化函数
	const formatDate = (dateString) => {
		if (!dateString) return '未设置';
		const date = new Date(dateString);
		if (isNaN(date.getTime())) return '未设置';
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	};

	// 任务类型映射
	const taskTypeMap = {
		1: '竞品调研',
		2: '仓库整理',
		3: '项目支援'
	};

	// 获取任务类型显示文本
	const getTaskTypeText = (type) => {
		return taskTypeMap[type] || '未知类型';
	};

	// 获取图片列表（处理逗号分隔的多图URL）
	const getImageList = (imagePaths) => {
		if (!imagePaths) return [];
		// 移除反引号，然后按逗号分割
		const paths = imagePaths.replace(/`/g, '').split(',').map(path => path.trim());
		// 过滤空字符串
		return paths.filter(path => path.length > 0);
	};

	// 预览单个图片
	const previewImage = (imageUrl) => {
		if (imageUrl) {
			uni.previewImage({
				urls: [imageUrl.replace(/`/g, '')],
				current: 0
			});
		}
	};

	// 预览图片列表
	const previewImageList = (imageList, currentIndex) => {
		if (imageList && imageList.length > 0) {
			uni.previewImage({
				urls: imageList,
				current: currentIndex
			});
		}
	};

	// 获取文件名列表（处理逗号分隔的多文件）
	const getFileList = (fileNames) => {
		if (!fileNames) return [];
		// 移除反引号，然后按逗号分割
		const names = fileNames.replace(/`/g, '').split(',').map(name => name.trim());
		// 过滤空字符串
		return names.filter(name => name.length > 0);
	};

	// 获取文件URL列表（处理逗号分隔的多文件URL）
	const getFileUrlList = (fileUrls) => {
		if (!fileUrls) return [];
		// 移除反引号，然后按逗号分割
		const urls = fileUrls.replace(/`/g, '').split(',').map(url => url.trim());
		// 过滤空字符串和无效URL
		return urls.filter(url => url.length > 0 && url !== 'www.baidu.com');
	};

	// 打开文件
	const openFile = (fileUrl) => {
		if (fileUrl && fileUrl !== 'www.baidu.com') {
			uni.downloadFile({
				url: fileUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						uni.openDocument({
							filePath: res.tempFilePath,
							showMenu: true,
							success: (result) => {
								console.log('打开文档成功');
							},
							fail: (err) => {
								console.error('打开文档失败:', err);
								uni.showToast({
									title: '打开文档失败',
									icon: 'none'
								});
							}
						});
					}
				},
				fail: (err) => {
					console.error('下载文件失败:', err);
					uni.showToast({
						title: '下载文件失败',
						icon: 'none'
					});
				}
			});
		}
	};

	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	}

	onLoad(() => {
		getBarHeight();
		// 从本地存储获取任务数据
		const storedTask = uni.getStorageSync('currentTaskData');
		if (storedTask) {
			taskData.value = storedTask;
		} else {
			// 如果本地存储没有数据，使用默认数据
			taskData.value = {
				id: 124,
				status: 1,
				taskType: '仓库整理',
				description: '项目支援项目支援项目支援项目支援项目支援项目支援项目支援',
				dueDate: '2025-10-10',
				assignerName: '动销超管',
				originalData: {
					createTime: 1758787659000,
					updateTime: 1760064300000,
					creator: '1',
					updater: '148',
					deleted: false,
					id: 124,
					description: '清由感人等质界习日各厂放府也族。带快和二活千要热统可下放低。个生书易物制象改图立马布包到报划。老本但片出参规空际现导根。制九后育市直然九府间十况许果新。之大之论儿越南照状持好共设拉产。',
					uid: 148,
					shopid: 130,
					completionTime: null,
					fileUrl: ' `http://yrvo.es/uuvu,http://example.com/file2.pdf,http://example.com/file3.docx` ',
												taskFile: '测试文件.pdf,报告.docx,表格.xlsx',
					taskDescription: '项目支援项目支援项目支援项目支援项目支援项目支援项目支援',
					imagePath: ' `http://dummyimage.com/400x400,http://dummyimage.com/300x300,http://dummyimage.com/200x200` ',
												taskFile: '测试文件.pdf',
					fileName: '写则任行安',
					taskId: 124,
					status: 1,
					nickName: '张五'
				},
				dxTaskDO: {
					createTime: 1758787668000,
					updateTime: 1760061235000,
					creator: '1',
					updater: '147',
					deleted: false,
					id: 124,
					taskType: 2,
					description: '项目支援项目支援项目支援项目支援项目支援项目支援项目支援',
					uids: '148',
					status: 0,
					completionTime: '2025-10-10 09:38:58',
					shopId: 133,
					fileUrl: 'www.baidu.com',
					surveryId: null,
					createUserName: '动销超管'
				}
			};
		}
	})
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 100vh;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.contBox {
		padding: 22rpx;
		box-sizing: border-box;
		padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);
		.contBig{
			margin-bottom: 24rpx;
			border-radius: 12.82rpx;
			overflow: hidden;
		}
		.contTop {
			width: 100%;
			background: #ffffff;
			box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #c0c0c03b;
			padding: 34rpx 32rpx;
			box-sizing: border-box;
			position: relative;
			.contTit{
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 28rpx;
				.contName{
					font-weight: 500;
					font-size: 33.33rpx;
					color: #1C2027;
					flex: 1;
					
				}
				.contStatus{
					width: 105.77rpx;
					height: 105.77rpx;
					position: absolute;
					right: 36rpx;
				top: 27rpx;
					image{
						width: 100%;
						height: 100%;
					}
				}
			}
			.contLi{
				color: #4a4a4a;
				 font-weight: 400;
				 font-size: 25.64rpx;
				 line-height: 44.87rpx;
				 display: flex;
				flex-wrap: wrap;
				text{
					color: #7f8494;
					margin-right: 8rpx;
					flex-shrink: 0;
				}
				.contImgBox{
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					.contImageLi{
						width: 190rpx;
						height: 137rpx;
						margin-right: 20rpx;
						margin-bottom: 16rpx;
						border-radius: 8rpx;
						overflow: hidden;
						image{
							width:100%;
							height: 100%;
						}
					}
				}
				.linkText {
								color: #4580F6;
								text-decoration: underline;
								word-break: break-all;
								flex: 1;
							}
							.fileList {
								display: flex;
								flex-direction: column;
								gap: 12rpx;
								margin-top: 12rpx;
							}
							.fileItem {
								padding: 12rpx 16rpx;
								background-color: #f5f8ff;
								border-radius: 8rpx;
								font-size: 24rpx;
								display: inline-block;
								max-width: 100%;
							}
							.contImageLi {
								width: 190rpx;
								height: 137rpx;
								margin-right: 20rpx;
								margin-bottom: 16rpx;
								border-radius: 8rpx;
								overflow: hidden;
								image {
									width: 100%;
									height: 100%;
								}
							}
			}
		}
	}
	
</style>